<script setup>
import {ref} from "vue"
import {channelAddService, channelEditService} from "@/api/channel"

// dialog对话框显示
const dialogVisible = ref(false)

const open = (row) => {
  dialogVisible.value = true
  formModel.value = row
}

// 暴露给父组件 打开dialog会话框
defineExpose({
  open
})

// 表单字段
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})

// 表单元素规则校验
const rules = {
  cate_name: [
    {required: true, message: '请输入文章分类', trigger: 'blur'},
    {min: 1, max: 10, message: '请输入1-10个非空格字符', trigger: 'blur'}
  ],
  cate_alias: [
    {required: true, message: '请输入文章别名', trigger: 'blur'},
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是1-15位的字母数字',
      trigger: 'blur'
    }
  ]
}

const emit = defineEmits(['success'])
// 提交表单
const form = ref()
const submit = async () => {
  // 表单校验
  await form.value.validate()

  if (formModel.value.id) {
    await channelEditService(formModel.value)
  } else {
    await channelAddService(formModel.value)
  }
  ElMessage.success(formModel.value.id ? '编辑成功' : '添加成功')
  dialogVisible.value = false
  // 通知列表回显
  emit("success")
}


</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form ref="form" :model="formModel" :rules="rules" label-width="100px"
             style="padding-right: 30px">
      <el-form-item prop="cate_name" label="文章分类">
        <el-input v-model="formModel.cate_name"
                  placeholder="请输入文章分类"></el-input>
      </el-form-item>
      <el-form-item prop="cate_alias" label="文章别名">
        <el-input v-model="formModel.cate_alias"
                  placeholder="请输入文章别名"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
